package com.zhj.threadpoolboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadPoolExecutorConfig {

    @Bean(name = "threadPoolExecutor")
    public Executor threadPoolExecutor() {
        ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolMonitor();
        int processNum = Runtime.getRuntime().availableProcessors(); // 返回可用处理器的Java虚拟机的数量
        int corePoolSize = (int) (processNum / (1 - 0.2));
        int maxPoolSize = (int) (processNum / (1 - 0.5));
        threadPoolExecutor.setCorePoolSize(corePoolSize); // 核心池大小
        threadPoolExecutor.setMaxPoolSize(maxPoolSize); // 最大线程数
        threadPoolExecutor.setThreadPriority(Thread.MAX_PRIORITY); //设置线程池中线程的优先级为最高
        threadPoolExecutor.setDaemon(false); //设置线程池中的线程不是守护线程。这意味着应用程序不会在所有非守护线程结束时立即退出
        threadPoolExecutor.setThreadNamePrefix("test-Executor-"); // 线程名字前缀
        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略：由提交任务的线程来执行
        threadPoolExecutor.setWaitForTasksToCompleteOnShutdown(true); // 停服时，是否等待任务执行完毕后关闭
        threadPoolExecutor.setAwaitTerminationSeconds(60); // 停服时，等待 awaitTerminationMillis 秒数，超时以后，任务丢掉
        threadPoolExecutor.initialize();
        return threadPoolExecutor;
    }


}
